package com.qdxwx.manage.controller.user;

import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.page.PageRequest;
import com.qdxwx.common.page.TableDataInfo;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.account.UserAccountDetailService;
import com.qdxwx.data.service.account.UserAccountService;
import com.qdxwx.manage.annotation.Log;
import com.qdxwx.common.annotation.Permissions;
import com.qdxwx.manage.controller.BaseController;

import com.qdxwx.manage.support.SessionUtils;
import com.qdxwx.models.account.UserAccount;
import com.qdxwx.models.account.UserAccountDTO;
import com.qdxwx.models.account.UserAccountDetail;
import com.qdxwx.models.enums.AccountBizType;
import com.qdxwx.models.enums.AccountHistoryType;
import com.qdxwx.models.enums.AccountType;
import com.qdxwx.models.enums.BusinessType;
import com.qdxwx.models.manager.Manager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import jakarta.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

/**
 * 账户信息Controller
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
@Controller
@RequestMapping("/user/account")
public class UserAccountController extends BaseController {
    @Autowired
    private UserAccountService userAccountService;
    @Autowired
    private UserAccountDetailService userAccountDetailService;
    @GetMapping("/list.html")
    public ModelAndView account() {
        return new ModelAndView("user/account-list");
    }

    /**
     * 查询账户信息列表
     */
    @PostMapping("/list.json")
    @Permissions("user:account")
    @ResponseBody
    public TableDataInfo list(HttpServletRequest request) {
        Manager manager = SessionUtils.getManager();
        if (manager == null){
            return TableDataInfo.error("登录超时");
        }
        String searchKey = TKString.trim(request.getParameter("searchKey"));

        UserAccountDTO query = new UserAccountDTO();
        if (searchKey.length() > 1) {
            if (TKString.isNumber(searchKey)) {
                if (TKString.isMobile(searchKey)) {
                    query.setMobile(searchKey);
                } else {
                    query.setUserId(TKConvert.toLong(searchKey));
                }
            } else {
                query.setUserName(searchKey);
            }
        }
        query.setAccountStatus(request.getParameter("accountStatus"));

        List<UserAccountDTO> list = userAccountService.getList(query, PageRequest.form(request));
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(list);
        rspData.setTotal(userAccountService.count(query));
        return rspData;
    }

    /**
     * 冻结or解冻
     */
    @Permissions("user:account")
    @Log(title = "更改用户账号状态", businessType = BusinessType.UPDATE)
    @PostMapping("/status.json")
    @ResponseBody
    public AjaxResult statusJson(HttpServletRequest request) {
        long userId = TKConvert.toInteger(request.getParameter("userId"));
        String accountStatus = request.getParameter("accountStatus");
        if(userId < 1 || TKString.isEmpty(accountStatus)) return error("参数异常");
        UserAccount userAccount = new UserAccount();
        userAccount.setUserId(userId);
        userAccount.setAccountStatus(accountStatus);
        return toAjax(userAccountService.update(userAccount));
    }

    /**
     * 账户充值或扣款
     */
    @GetMapping("/recharge.html")
    public String AccountInfo(HttpServletRequest request, ModelMap mmap) {
        long userId = TKConvert.toLong(request.getParameter("userId"));
        String flag = request.getParameter("flag");
        if(userId < 1 || TKString.isEmpty(flag)) return error404;
        UserAccountDTO userAccountDTO = userAccountService.getDTOByUserId(userId);
        if(userAccountDTO == null || !"ACTIVE".equals(userAccountDTO.getAccountStatus())) return error404;
        mmap.put("userAccountDTO", userAccountDTO);
        mmap.put("flag", flag);
        return "user/account-recharge";
    }

    /**
     * 充值扣款
     */
    @Permissions("user:account:recharge")
    @Log(title = "用户账号充值", businessType = BusinessType.UPDATE)
    @PostMapping("/recharge.json")
    @ResponseBody
    public AjaxResult Recharge(HttpServletRequest request) {
        Manager manager = SessionUtils.getManager();
        if (manager == null){
            return AjaxResult.error("登录超时！");
        }
        long userId = TKConvert.toLong(request.getParameter("userId"));
        if (userId < 1) {
            return AjaxResult.error("缺少用户id！");
        }
        int money = TKConvert.toBigDecimal(request.getParameter("money")).multiply(BigDecimal.valueOf(100)).intValue();
         //说明
        String remark = TKString.trim(request.getParameter("remark"));
        String flag = TKString.trim(request.getParameter("flag"));
        if (money <= 0){
            return AjaxResult.error("金额必需大于0！");
        }
        UserAccount userAccount = userAccountService.getByUserId(userId);
        if (userAccount == null) {
            return AjaxResult.error("找不到指定用户，请与管理员核对（userId:" + userId + "）！");
        }
        try {
            if ("credit".equals(flag)) {
                userAccountService.income(userAccount, money, AccountType.VM, AccountHistoryType.ADMINLOAD, 0, "后台充值", false, AccountBizType.ADMIN);
                userAccountService.addUserAccountOpt(userAccount.getUserId(), manager, money, AccountHistoryType.ADMINLOAD.toString(), remark);
            } else if ("debit".equals(flag)) {
                if (money > userAccount.getBalance()) {
                    return AjaxResult.error("扣款金额不得大于账户余额！");
                }
                userAccountService.deduct(userAccount, money, AccountHistoryType.ADMINREFUND, 0, "后台扣款", false, AccountBizType.ADMIN);
                userAccountService.addUserAccountOpt(userAccount.getUserId(), manager, money, AccountHistoryType.ADMINREFUND.toString(), remark);
            } else {
                return AjaxResult.error("系统参数错误！");
            }
            return AjaxResult.success();
        }catch (Exception ex){
            return AjaxResult.error(ex.getMessage());
        }
    }

    /***
     * 查询账户记录
     */
    @GetMapping("/info/list.html")
    public String accountDetailed(HttpServletRequest request, ModelMap mmap) {
        long userId = TKConvert.toLong(request.getParameter("userId"));
        if(userId < 1) return error404;
        mmap.put("userId", userId);
        return "user/account-history";
    }

    /**
     * 查询账户信息列表
     */
    @Permissions("user:account")
    @Log(title = "用户账户明细", businessType = BusinessType.UPDATE)
    @PostMapping("/info/list.json")
    @ResponseBody
    public TableDataInfo accountDetailed(HttpServletRequest request) {
        long userId = TKConvert.toLong(request.getParameter("userId"));
        if(userId < 1) return null;
        UserAccountDetail accountHistory = new UserAccountDetail();
        accountHistory.setUserId(userId);
        accountHistory.setActHistoryType(request.getParameter("actHistoryType"));
        accountHistory.setBizType(request.getParameter("bizType"));
        List<UserAccountDetail> list = userAccountDetailService.getList(accountHistory, PageRequest.form(request));
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(list);
        rspData.setTotal(userAccountDetailService.count(accountHistory));
        return rspData;
    }

}
